package com.zx.sdk.league.member;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.view.ViewGroup;

import androidx.annotation.Nullable;

import com.wangmai.appsdkdex.WMAdSdk;
import com.wangmai.appsdkdex.WMCustomPrivateController;
import com.wangmai.appsdkdex.ads.WMAdInterstitial;
import com.wangmai.appsdkdex.ads.WMAdRewardVideo;
import com.wangmai.appsdkdex.ads.WMAdSplashad;
import com.wangmai.common.Ibase.IBaseInterface;
import com.wangmai.common.Ilistener.XAdInterstitialListener;
import com.wangmai.common.Ilistener.XAdRewardVideoListener;
import com.wangmai.common.Ilistener.XAdSplashListener;
import com.wangmai.common.utils.ConstantInfo;
import com.wangmai.common.utils.WMLocation;
import com.zx.sdk.ZxSDK;
import com.zx.sdk.listener.BaseZxRewardListener;
import com.zx.sdk.listener.BaseZxSplashListener;
import com.zx.sdk.model.AdInfo;
import com.zx.sdk.model.ReadyAdPosition;
import com.zx.sdk.model.ZxError;
import com.zx.sdk.util.LogHelper;

import java.util.HashMap;

public class WangMai extends BaseLeagueMember<WMAdSplashad, WMAdRewardVideo, Object, WMAdInterstitial, Object> {

    @Override
    public String getName() {
        return "wm";
    }

    @Override
    protected void onInit(Context context, String appId, boolean initialized) {
        if (!initialized) {
            String key = appId.split("@@")[0];
            String token = appId.split("@@")[1];
            WMAdSdk mWMAdSdk = new WMAdSdk.Builder()
                    .setkey(key)                                // AppKey
                    .setToken(token)                        // AppToken
                    .enablePersonalized(true)                       // 开启个性化广告推荐
                    .enableCrashIntercept(true)                      // 开启异常拦截功能，可以避免大部分常见的错误引起的崩溃
                    .debug(ZxSDK.isDebug())                        // 开启debug模式，便于查看日志，发布版本请记得关闭。
                    .setPrivateController(new WMCustomPrivateController() {
                        @Override
                        public boolean isCanUseLocation() {
                            return super.isCanUseLocation();
                        }

                        @Override
                        public WMLocation getLocation() {
                            return super.getLocation();
                        }

                        @Override
                        public boolean isCanUsePhoneState() {
                            return true;
                        }

                        @Override
                        public String getDevImei() {
                            return super.getDevImei();
                        }

                        @Override
                        public boolean isCanUseOaid() {
                            return true;
                        }

                        @Override
                        public String getDevOaid() {
                            return ZxSDK.oaid;
                        }

                        @Override
                        public boolean isCanUseWifiState() {
                            return true;
                        }

                        @Override
                        public String getDevMacAddress() {
                            return super.getDevMacAddress();
                        }

                        @Override
                        public boolean isCanUseNetworkState() {
                            return true;
                        }

                        @Override
                        public boolean isCanUseWriteExternal() {
                            return true;
                        }

                        @Override
                        public boolean isCanUseAppList() {
                            return true;
                        }

                        @Override
                        public boolean isCanUsePermissionRecordAudio() {
                            return super.isCanUsePermissionRecordAudio();
                        }
                    }) // 隐私信息控制设置
                    .build(context);
            mWMAdSdk.init();
        }
    }

    @Override
    protected void onLoadSplash(AdInfo adInfo, ViewGroup container, String mode, String type, BaseZxSplashListener listener) {
        Context activity = container.getContext();
        if (!(activity instanceof Activity)) return;
        WMAdSplashad[] wmAdSplashad = new WMAdSplashad[1];
        wmAdSplashad[0] = new WMAdSplashad((Activity) activity, adInfo.getMapPid(), new XAdSplashListener() {
            @Override
            public void onAdRequest() {
                switch (mode) {
                    case ZxSDK.FETCH_ONLY ->
                            saveSplash(adInfo.getMapPid(), wmAdSplashad[0], container);
                    case ZxSDK.FETCH_AND_SHOW ->
                            onShowSplash(adInfo, container, wmAdSplashad[0], listener);
                }
                listener.onADLoaded(WangMai.this, -1, adInfo);
            }

            @Override
            public void onExposure() {
                listener.onADExposure(WangMai.this, adInfo);
            }

            @Override
            public void onClick() {
                listener.onADClicked(WangMai.this, adInfo);
            }

            @Override
            public void onAdDismissed() {
                listener.onADDismissed(WangMai.this, adInfo);
            }

            @Override
            public void onAdZoomOut() {
                // 广告进入小窗回调（部分需求方平台支持）
            }

            @Override
            public void onAdZoomOutClick() {
                // 广告进入小窗点击回调（部分需求方平台支持）
            }

            @Override
            public void onAdZoomOutDismissed() {
                // 广告小窗关闭回调（部分需求方平台支持）
            }

            @Override
            public void onNoAd(String s) {
                switch (mode) {
                    case ZxSDK.FETCH_ONLY ->
                            listener.onPreLoadNoAD(WangMai.this, new ZxError("-1", s), adInfo);
                    case ZxSDK.FETCH_AND_SHOW ->
                            listener.onNoAD(WangMai.this, new ZxError("-1", s), adInfo);
                }
            }
        });
    }

    @Override
    public boolean onShowSplash(AdInfo adInfo, ViewGroup container, @Nullable WMAdSplashad splash, BaseZxSplashListener listener) {
        if (splash != null) {
            splash.show(container);
            return true;
        }
        return false;
    }

    @Override
    public void onLoadReward(Activity context, AdInfo adInfo, String mode, String type, BaseZxRewardListener listener) {
        WMAdRewardVideo[] wmAdRewardVideo = new WMAdRewardVideo[1];
        wmAdRewardVideo[0] = new WMAdRewardVideo(context, adInfo.getMapPid(), ConstantInfo.VERTICAL, new XAdRewardVideoListener() {
            @Override
            public void onAdRequest() {
                // 广告请求成功回调
            }

            @Override
            public void onAdLoad() {
                // 广告加载完成回调，展示广告
                switch (mode) {
                    case ZxSDK.FETCH_ONLY -> saveReward(adInfo.getMapPid(), wmAdRewardVideo[0]);
                    case ZxSDK.FETCH_AND_SHOW -> wmAdRewardVideo[0].show(context);
                }
                listener.onADLoad(WangMai.this, adInfo);
            }

            @Override
            public void onExposure() {
                listener.onADExpose(WangMai.this, adInfo);
            }

            @Override
            public void onRewarded(boolean isRewardValid, Bundle bundle) {
                if (isRewardValid) {
                    listener.onReward(WangMai.this, new HashMap<>(), adInfo);
                }
            }

            @Override
            public void onClick() {
                listener.onADClick(WangMai.this, adInfo);
            }

            @Override
            public void onVideoComplete() {
                listener.onVideoComplete(WangMai.this, adInfo);
            }

            @Override
            public void onAdClose() {
                listener.onADClose(WangMai.this, adInfo);
            }

            @Override
            public void onVideoError(String s) {
                listener.onVideoPlayError(WangMai.this, new ZxError("-1", s), adInfo);
            }

            @Override
            public void onNoAd(String s) {
                switch (mode) {
                    case ZxSDK.FETCH_ONLY ->
                            listener.onPreLoadADError(WangMai.this, new ZxError("-1", s), adInfo);
                    case ZxSDK.FETCH_AND_SHOW ->
                            listener.onNoAD(WangMai.this, new ZxError("-1", s), adInfo);
                }
            }
        });
        wmAdRewardVideo[0].load();
    }

    @Override
    public boolean onShowReward(Activity context, AdInfo adInfo, @Nullable WMAdRewardVideo reward, BaseZxRewardListener listener) {
        if (reward != null) {
            reward.show(context);
            return true;
        }
        return false;
    }

    @Override
    public void onLoadInterstitial(Activity context, AdInfo adInfo, String mode, String type, BaseZxRewardListener listener) {
        WMAdInterstitial[] wmAdInterstitials = new WMAdInterstitial[1];
        wmAdInterstitials[0] = new WMAdInterstitial(context, adInfo.getMapPid(), new XAdInterstitialListener() {
            @Override
            public void onAdRequest() {
                listener.onADLoad(WangMai.this, adInfo);
                switch (mode) {
                    case ZxSDK.FETCH_ONLY ->
                            saveInterstitial(adInfo.getMapPid(), wmAdInterstitials[0]);
                    case ZxSDK.FETCH_AND_SHOW -> wmAdInterstitials[0].show(context);
                }
            }

            @Override
            public void onExposure() {
                listener.onADExpose(WangMai.this, adInfo);
            }

            @Override
            public void onClick() {
                listener.onADClick(WangMai.this, adInfo);
            }

            @Override
            public void onAdClose() {
                listener.onADClose(WangMai.this, adInfo);
            }

            @Override
            public void onNoAd(String s) {
                switch (mode) {
                    case ZxSDK.FETCH_ONLY ->
                            listener.onPreLoadADError(WangMai.this, new ZxError("-1", s), adInfo);
                    case ZxSDK.FETCH_AND_SHOW ->
                            listener.onNoAD(WangMai.this, new ZxError("-1", s), adInfo);
                }
            }
        });
        wmAdInterstitials[0].load();
    }

    @Override
    public boolean onShowInterstitial(Activity context, AdInfo adInfo, @Nullable WMAdInterstitial interstitial, BaseZxRewardListener listener) {
        if (interstitial != null) {
            interstitial.show(context);
            return true;
        }
        return false;
    }

    @Override
    public int getCpmByPid(String type, String pid) {
        int def = super.getCpmByPid(type, pid);
        switch (type) {
            case ZxSDK.SPLASH:
                def = splashMap.get(pid) == null ? def : splashMap.get(pid).getECPM();
            case ZxSDK.REWARD:
                def = rewardMap.get(pid) == null ? def : rewardMap.get(pid).getECPM();
            case ZxSDK.INTERSTITIAL:
                def = interstitialMap.get(pid) == null ? def : interstitialMap.get(pid).getECPM();
        }
        cpmCache.put(type + pid, def);
        return def;
    }

    @Override
    public boolean isPreResReady(String type, String pid) {
        return switch (type) {
            case ZxSDK.SPLASH -> splashMap.get(pid) != null;
            case ZxSDK.REWARD -> rewardMap.get(pid) != null;
            case ZxSDK.INTERSTITIAL -> interstitialMap.get(pid) != null;
            default -> false;
        };
    }

    @Override
    public void notifyBiddingWin(String type, String mapPid, @Nullable ReadyAdPosition loser) throws Exception {
        IBaseInterface iBidding = getIBidding(type, mapPid);
        if (iBidding == null) {
            return;
        }
        iBidding.sendWinNotificationWithInfo(null);
        LogHelper.d(getName(), "notifyBiddingWin", mapPid);
    }

    @Nullable
    private IBaseInterface getIBidding(String type, String pid) {
        IBaseInterface iBidding = null;
        if (ZxSDK.REWARD.equals(type)) {
            iBidding = rewardMap.get(pid);
        } else if (ZxSDK.SPLASH.equals(type)) {
            iBidding = splashMap.get(pid);
        } else if (ZxSDK.INTERSTITIAL.equals(type)) {
            iBidding = interstitialMap.get(pid);
        }
        return iBidding;
    }

    @Override
    public void notifyBiddingLose(String type, String mapPid, ReadyAdPosition winner, ZxSDK.LoseReason reason) throws Exception {
        IBaseInterface iBidding = getIBidding(type, mapPid);
        if (iBidding == null) {
            return;
        }
        iBidding.sendLossNotificationWithInfo(null);
        LogHelper.d(getName(), "notifyBiddingLose", mapPid);
    }

    @Override
    public void destroySplash(Activity activity) {

    }

    @Override
    public void destroyShownSplash(Activity activity, WMAdSplashad splashAd) {
        if (splashAd != null) {
            splashAd.destroy();
        }
    }

    @Override
    public void destroyReward(Activity activity) {
    }

    @Override
    public void destroyShownReward(Activity activity, WMAdRewardVideo rewardAd) {
        if (rewardAd != null) {
            rewardAd.destroy();
        }
    }
}
